package com.example.hellodemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class HanderActivity extends AppCompatActivity {
    private Handler handler;
    private Button handerBtn1,handerBtn2;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hander);
        handler = new Handler(){
            @NonNull
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
                        Log.d("hander","线程通信");

                        finish(); // 返回上一个界面
                        break;
                }
            }
        };

        handerBtn1 = findViewById(R.id.hander_btn1);
        handerBtn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("hander","延迟调用");
                // 延迟条用
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(HanderActivity.this,"发送消息",Toast.LENGTH_LONG).show();
                    }
                },3000);

            }
        });

        handerBtn2 = findViewById(R.id.hander_btn2);
        handerBtn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    new Thread(){
                        @Override
                        public void run() {
                            super.run();
                            Message message = new Message();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    }.start();
            }
        });

    }
}
